package com.cskaoyan.service.admin.impl;

import com.cskaoyan.bean.*;
import com.cskaoyan.bean.param.CommonData;
import com.cskaoyan.bean.vo.AdminOrderChannelVO;
import com.cskaoyan.bean.vo.AdminOrderDetailVO;
import com.cskaoyan.bean.vo.AdminOrderUserInDetailVO;
import com.cskaoyan.mapper.*;
import com.cskaoyan.service.admin.AdminOrderService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 商场管理 --> 订单管理
 *
 * @author : Caspar
 * @since : 2022.06.27 10:46
 */
@Service
public class AdminOrderServiceImpl implements AdminOrderService {

    @Autowired
    MarketOrderMapper marketOrderMapper;

    @Autowired
    MarketOrderGoodsMapper marketOrderGoodsMapper;

    @Autowired
    MarketUserMapper marketUserMapper;

    @Autowired
    MarketCommentMapper marketCommentMapper;

    @Autowired
    MarketGoodsProductMapper marketGoodsProductMapper;

    /**
     * 返回快递及其代码信息
     *
     * @return java.util.List<com.cskaoyan.bean.vo.AdminOrderChannelVO>
     * @author: Caspar CXC
     * @since 2022/06/27 21:20
     */
    @Override
    public List<AdminOrderChannelVO> channel() {
        List<AdminOrderChannelVO> list = new ArrayList<>();
        list.add(new AdminOrderChannelVO("ZTO", "中通快递"));
        list.add(new AdminOrderChannelVO("YTO", "圆通快递"));
        list.add(new AdminOrderChannelVO("YD", "韵达快递"));
        list.add(new AdminOrderChannelVO("YZPY", "邮政快递包裹"));
        list.add(new AdminOrderChannelVO("EMS", "EMS"));
        list.add(new AdminOrderChannelVO("DBL", "德邦快递"));
        list.add(new AdminOrderChannelVO("FAST", "快捷快递"));
        list.add(new AdminOrderChannelVO("ZJS", "宅急送"));
        list.add(new AdminOrderChannelVO("TNT", "TNT快递"));
        list.add(new AdminOrderChannelVO("UPS", "UPS"));
        list.add(new AdminOrderChannelVO("DHL", "DHL"));
        list.add(new AdminOrderChannelVO("FEDEX", "FEDEX联邦(国内件)"));
        list.add(new AdminOrderChannelVO("FEDEX_GJ", "FEDEX联邦(国际件)"));
        return list;
    }

    /**
     * 查询订单信息，封装进CommonData
     *
     * @return com.cskaoyan.bean.param.CommonData<com.cskaoyan.bean.MarketOrder>
     * @author: Caspar CXC
     * @since 2022/06/27 16:13
     */
    @Override
    public CommonData<MarketOrder> list(BasePageInfo basePageInfo, Integer userId, String orderSn, Date start, Date end, Short[] orderStatusArray) {

        PageHelper.startPage(basePageInfo.getPage(), basePageInfo.getLimit());

        MarketOrderExample example = new MarketOrderExample();
        example.setOrderByClause("pay_time desc");
        MarketOrderExample.Criteria criteria = example.createCriteria();

        if (!StringUtils.isEmpty(userId)) {
            criteria.andUserIdEqualTo(userId);
        }
        if (!StringUtils.isEmpty(orderSn)) {
            criteria.andOrderSnEqualTo(orderSn);
        }
        if (!StringUtils.isEmpty(start) && !StringUtils.isEmpty(end)) {
            criteria.andPayTimeBetween(start, end);
        }
        if (orderStatusArray != null) {

            List<Short> list = new ArrayList<>();
            for (Short aShort : orderStatusArray) {
                list.add(aShort);
            }
            criteria.andOrderStatusIn(list);
        }
        criteria.andDeletedEqualTo(false);

        List<MarketOrder> marketOrders = marketOrderMapper.selectByExample(example);
        PageInfo<MarketOrder> marketOrderPageInfo = new PageInfo<>(marketOrders);
        CommonData data = CommonData.data(marketOrderPageInfo);
        return data;
    }

    /**
     * 通过订单的id查出详细信息，订单id是唯一的
     *
     * @param id
     * @return com.cskaoyan.bean.vo.AdminOrderDetailVO
     * @author: Caspar CXC
     * @since 2022/06/27 19:45
     */
    @Override
    public AdminOrderDetailVO detail(String id) {
        Integer orderId = Integer.parseInt(id);
        AdminOrderDetailVO adminOrderDetailVO = new AdminOrderDetailVO();

        MarketOrderGoodsExample example = new MarketOrderGoodsExample();
        MarketOrderGoodsExample.Criteria criteria = example.createCriteria();
        criteria.andOrderIdEqualTo(orderId);
        List<MarketOrderGoods> marketOrderGoods = marketOrderGoodsMapper.selectByExample(example);

        MarketOrder marketOrder = marketOrderMapper.selectByPrimaryKey(orderId);

        if (marketOrder == null) {
            adminOrderDetailVO = null;
            return adminOrderDetailVO;
        }

        Integer userId = marketOrder.getUserId();
        // 从market_user表格中查找nickname、avatar（前端就需要这两个）
        AdminOrderUserInDetailVO adminOrderUserInDetailVO = marketUserMapper.selectUser(userId);

        adminOrderDetailVO.setOrderGoods(marketOrderGoods);
        adminOrderDetailVO.setUser(adminOrderUserInDetailVO);
        adminOrderDetailVO.setOrder(marketOrder);

        return adminOrderDetailVO;
    }

    /**
     * 订单发货，通过订单id 和传过来的参数修改各种信息（发货快递、快递编号、订单状态）
     *
     * @param orderId
     * @param shipChannel
     * @param shipSn
     * @return void
     * @author: Caspar CXC
     * @since 2022/06/28 16:29
     */
    @Override
    public void ship(Integer orderId, String shipChannel, String shipSn) {

        MarketOrder marketOrder = new MarketOrder();
        marketOrder.setId(orderId);
        marketOrder.setShipChannel(shipChannel);
        marketOrder.setShipSn(shipSn);

        // 订单状态改为301（已发货）
        short num = 301;
        marketOrder.setOrderStatus(num);

        marketOrder.setShipTime(new Date());

        // 修改更新时间
        marketOrder.setUpdateTime(new Date());

        marketOrderMapper.updateByPrimaryKeySelective(marketOrder);
    }

    /**
     * 订单退款，通过订单编号
     *
     * @param orderId
     * @param money
     * @return void
     * @author: Caspar CXC
     * @since 2022/06/28 16:26
     */
    @Override
    public void refund(Integer orderId, Object money) {

        BigDecimal refundMoney;

        if (money instanceof Double) {
            refundMoney = BigDecimal.valueOf((Double) money);
        } else {
            refundMoney = BigDecimal.valueOf((Integer) money);
        }

        MarketOrder marketOrder = marketOrderMapper.selectByPrimaryKey(orderId);
        marketOrder.setRefundAmount(refundMoney);

        // 更改订单状态为203（已退款）
        marketOrder.setOrderStatus((short) 203);

        // 更改售后状态为3（管理员退款成功）
        marketOrder.setAftersaleStatus((short) 3);
        marketOrder.setRefundTime(new Date());
        marketOrder.setUpdateTime(new Date());

        // 退款成功，订单已结束
        marketOrder.setEndTime(new Date());

        marketOrderMapper.updateByPrimaryKeySelective(marketOrder);

        // 修改产品数量
        MarketOrderGoodsExample orderGoodsExample = new MarketOrderGoodsExample();
        orderGoodsExample.createCriteria().andOrderIdEqualTo(orderId);
        List<MarketOrderGoods> orderGoodsList = marketOrderGoodsMapper.selectByExample(orderGoodsExample);
        for (MarketOrderGoods orderGoods : orderGoodsList) {
            MarketGoodsProduct product = marketGoodsProductMapper.selectByPrimaryKey(orderGoods.getProductId());
            int newNumber = product.getNumber() + orderGoods.getNumber();
            MarketGoodsProduct product1 = new MarketGoodsProduct();
            product1.setId(product.getId());
            product1.setNumber(newNumber);
            product1.setUpdateTime(new Date());
            marketGoodsProductMapper.updateByPrimaryKeySelective(product1);
        }
    }

    /**
     * 删除订单
     *
     * @param orderId
     * @return java.lang.Integer
     * @author: Caspar CXC
     * @since 2022/06/27 23:18
     */
    @Override
    public Integer delete(Integer orderId) {

        MarketOrder marketOrder = marketOrderMapper.selectByPrimaryKey(orderId);

        // 这是可以删除的
        if (marketOrder.getOrderStatus() != 101 && marketOrder.getOrderStatus() != 201 && marketOrder.getOrderStatus() != 202 && marketOrder.getOrderStatus() != 301) {

            marketOrder.setUpdateTime(new Date());
            marketOrder.setDeleted(true);
            marketOrderMapper.updateByPrimaryKeySelective(marketOrder);
            // 删除订单数据，返回0证明
            return 0;
        }

        // 不可以删除订单，返回不为0的数
        return 100;
    }

    /**
     * 根据商品评论进行回复
     *
     * @param commentId
     * @param adminContent
     * @return java.lang.Integer
     * @author: Caspar CXC
     * @since 2022/06/28 16:31
     */
    @Override
    public Integer reply(Integer commentId, String adminContent) {
        Integer code;
        MarketComment marketComment = marketCommentMapper.selectByPrimaryKey(commentId);
        if (!StringUtils.isEmpty(marketComment.getAdminContent())) {
            code = 622;
            return code;
        }
        marketComment.setAdminContent(adminContent);
        marketComment.setUpdateTime(new Date());
        marketCommentMapper.updateByPrimaryKeySelective(marketComment);

        code = 0;
        return code;
    }
}
